use anyhow::Result;
pub fn get_local_conf() -> Result<Conf> {
    
    let user_home: String = std::env::var("USERPROFILE")?;
    let user_home: String = user_home;
    let rep: String = "mod_manager".to_string();

    let us: String = user_home.clone();
    let re: String = rep.clone();
    let root_dir: String = format!("{0}\\AppData\\Local\\{1}",us,re);
    
    //从user_home中读取配置文件
    use std::fs::OpenOptions;
    use std::path::Path;
    use serde_json::{from_reader, to_writer};
    use std::io::{BufReader, BufWriter};
    let conf_path: &Path = Path::new(&root_dir[..]);
    //检查根目录
    if !conf_path.exists() {
        //根目录不存在
        std::fs::create_dir_all(conf_path)?;
    }
    

    let path: String = format!("{0}\\AppData\\Local\\{1}\\config.json",user_home,rep);
    let p: String = format!("{}\\cache", root_dir.clone());

    let rep: &Path = Path::new(&path[..]);
    //默认信息
    let co: Conf = Conf{
        version:std::env::var("MOD_MANAGER_TOOL_VERSION")?,
        global_path:p,
        mirrors:vec!["mirror1".to_string(),"mirror2".to_string(),"mirror3".to_string()]
    };

    //创建文件的闭包
    let create_file = |path: &Path, con: &Conf| {
        let mut file: std::fs::File = OpenOptions::new().read(true).write(true).create(true).open(path).unwrap();

        let buffer: BufWriter<&mut std::fs::File> = BufWriter::new(&mut file);
        to_writer(buffer, con).unwrap();
    };

    //检查仓库配置文件
    if rep.is_file() {
        //当文件存在时读取文件
        let mut file: std::fs::File = OpenOptions::new().read(true).write(false).create(false).open(rep)?;
        let buffer: BufReader<&mut std::fs::File> = BufReader::new(&mut file);
        let Conf{
            version,
            global_path,
            mirrors
        } = from_reader::<_,Conf>(buffer)?;

        let gp: String = global_path.clone();
        let mp: Vec<String> = mirrors.clone();

        let local_co: Conf = Conf{version,global_path,mirrors};
        use crate::utils::conf_util;
        let res: std::result::Result<(), ()> = conf_util::conf_check(&local_co);
        if let Err(()) = res {
            //出现版本不匹配时重新建立
            std::fs::remove_file(rep).unwrap();
            let new_conf: Conf = Conf {
                version:std::env::var("MOD_MANAGER_TOOL_VERSION")?,
                global_path:gp,
                mirrors:mp
            };
            create_file(rep, &new_conf);
        }
        return Ok(local_co);
    } else {
        //当文件不存在时创建一个默认文件
        create_file(rep, &co);
    }
    
    Ok(co)
}

use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize)]
pub struct Conf {
    pub version:String,
    pub global_path:String,
    pub mirrors:Vec<String>
}